package cn.sym.basic.util;

import cn.sym.basic.jwt.JwtUtils;
import cn.sym.basic.jwt.LoginData;
import cn.sym.basic.jwt.Payload;
import cn.sym.basic.jwt.RsaUtils;
import org.springframework.util.StringUtils;

import javax.servlet.http.HttpServletRequest;
import java.security.PublicKey;

/**
 * 登录Context
 * 获取当前登录人的信息和权限
 */
public class LoginContext {
    public static final String PBUKEY="hrm_auth_rsa.pub";

    /**
     * 返回对象可能使user或者employee
     * @param request
     * @return
     */
    public static  Object getLogin(HttpServletRequest request){
        String jwtToken = request.getHeader("U-TOKEN");
        if (StringUtils.isEmpty(jwtToken)){
            return null;
        }
        PublicKey publicKey = null;
        LoginData loginData = null;
        try {
            publicKey = RsaUtils.getPublicKey(JwtUtils.class.getClassLoader().getResource(PBUKEY).getFile());
            //获取载荷
            Payload<LoginData> payload = JwtUtils.getInfoFromToken(jwtToken, publicKey, LoginData.class);
            //载荷部分的登录信息
            loginData = payload.getLoginData();
            if (loginData==null){
                return null;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return loginData;
    }

}
